package com.uniknow.app.ui;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uniknow.app.AppConfig;
import com.uniknow.app.AppContext;
import com.uniknow.app.R;
import com.uniknow.app.bin.ImageText;
import com.uniknow.app.operate.BaseListener;
import com.uniknow.app.operate.HttpPath;
import com.uniknow.app.operate.WixMessageOperate;
import com.uniknow.app.operate.impl.WixMessageOperateImpl;
import com.uniknow.app.util.AudioRecorder;
import com.uniknow.app.util.FileUtils;
import com.uniknow.app.util.ImageUtils;
import com.uniknow.app.util.MD5;
import com.uniknow.app.util.StringUtils;
import com.uniknow.app.util.UIHelper;
import com.uniknow.app.util.UploadUtil;
import com.uniknow.app.widget.LoadingDialog;
import com.uniknow.app.widget.NewDataToast;

/**
 * 发送图文混排消息
 * @author lianjiao
 *
 */
public class TextImageActivity extends BaseActivity{
	
	private static int MAX_TIME = 60;    //最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 1;     //最短录制时间，单位秒，0为无时间限制，建议设为1
	
	private static int RECORD_NO = 0;  //不在录音
	private static int RECORD_ING = 1;   //正在录音
	private static int RECODE_ED = 2;   //完成录音
	
	private static int RECODE_STATE = 0;      //录音的状态
	
	private static float recodeTime=0.0f;    //录音的时间
	private static double voiceValue=0.0;    //麦克风获取的音量值
	
	private Context mContext;
	private Dialog dialog;
	private AudioRecorder audioRecorder;
	private MediaPlayer mediaPlayer;
	private Button SmallMoodAddImg,SmallMoodAddRecord,SmallMoodAddRecordHas,SmallMoodAddBack,SmallMoodAddSubmit;
	private EditText SmallMoodAddEdit;
	private ImageView SmallMoodAddImgHas;
	private Bitmap mBitmap;
	private String date="";
	private String realImgPath,realVoicePath;
	private File ImgFilePath;
	private final static int RESULT_GET_CAMERA = 0;
	private final static int RESULT_LOAD_IMAGE = 1;
	private boolean isCamera = true;
	private static boolean playState = false;  //播放状态
	private ImageView dialog_img;
	private Thread recordThread;
	private Builder alertDialog;
	private static LoadingDialog SubmitingDialog;
	private String UserID = "";
	private String PassWD = "";
	
	private String resId = "-1";
	private String sid = "-1";
	
	private String imgServiceId = "";
	
	private static Intent resultIntent;
	
	private WixMessageOperate messageOperate;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_textimage);
		messageOperate = new WixMessageOperateImpl(mContext);
		Intent intent = getIntent();
		resultIntent = new Intent();
		sid = intent.getStringExtra("sid");
		mContext = TextImageActivity.this;
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		SmallMoodAddImg = (Button) findViewById(R.id.smallmood_add_img);
		SmallMoodAddImgHas = (ImageView) findViewById(R.id.smallmood_add_img_has);
		SmallMoodAddRecord = (Button) findViewById(R.id.smallmood_add_record);
		SmallMoodAddRecordHas = (Button) findViewById(R.id.smallmood_add_record_has);
		SmallMoodAddBack = (Button)findViewById(R.id.smallmood_add_back);
		SmallMoodAddSubmit = (Button)findViewById(R.id.smallmood_add_submit);
		SmallMoodAddEdit = (EditText)findViewById(R.id.smallmood_add_edit);
		
		SmallMoodAddRecord.setOnTouchListener(TouchRecordListener);
		SmallMoodAddRecordHas.setOnClickListener(BtnClick());
		SmallMoodAddImg.setOnClickListener(BtnClick());
		SmallMoodAddImgHas.setOnClickListener(BtnClick());
		SmallMoodAddBack.setOnClickListener(BtnClick());
		SmallMoodAddSubmit.setOnClickListener(BtnClick());
		
		if(sid!=null && sid.equals("-1")){//不是评论是新发布的
			
		}else{//评论
			
		}
		SubmitingDialog = new LoadingDialog(mContext);
		SubmitingDialog.setCanceledOnTouchOutside(true);
		SubmitingDialog.setLoadText(mContext.getString(R.string.loading_submit));
	}
	
	OnTouchListener TouchRecordListener = new OnTouchListener(){

		@Override
		public boolean onTouch(View arg0, MotionEvent event) {
			switch (event.getAction())
			{
			case MotionEvent.ACTION_DOWN:
				if (RECODE_STATE != RECORD_ING) {
					date=new SimpleDateFormat("yy-MM-dd-HH-mm-ss",Locale.getDefault()).format(new Date());
					audioRecorder = new AudioRecorder(date);
					RECODE_STATE=RECORD_ING;
					showVoiceDialog();
					try {
						audioRecorder.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
					mythread();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (RECODE_STATE == RECORD_ING) {
					RECODE_STATE=RECODE_ED;
					if (dialog.isShowing()) {
						dialog.dismiss();
					}
					try {
							audioRecorder.stop();
							voiceValue = 0.0;
						} catch (IOException e) {
							e.printStackTrace();
						}
						if (recodeTime < MIX_TIME) {
							showWarnToast();
							SmallMoodAddRecord.setText("按住开始录音");
							RECODE_STATE=RECORD_NO;
							File file = new File(Environment.getExternalStorageDirectory(), AppConfig.FOLDER_VOICE_RECORD+"/"+date+".amr");
							file.delete();
						}else{
							//SmallMoodAddRecord.setText("录音完成!点击重新录音");
							SmallMoodAddRecord.setVisibility(View.GONE);
							SmallMoodAddRecordHas.setVisibility(View.VISIBLE);
							realVoicePath = getAmrPath();
						}
				}
				break;
			}
			return false;
		}
	};
	//录音时显示Dialog
	private void showVoiceDialog(){
		dialog = new Dialog(mContext,R.style.DialogRecordStyle);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		dialog.setContentView(R.layout.audio_dialog);
		dialog_img=(ImageView)dialog.findViewById(R.id.dialog_img);
		dialog.show();
	}
		
	//录音时间太短时Toast显示
	private void showWarnToast(){
		Toast toast = new Toast(mContext);
		 LinearLayout linearLayout = new LinearLayout(mContext);
		 linearLayout.setOrientation(LinearLayout.VERTICAL); 
		 linearLayout.setPadding(20, 20, 20, 20);
		
		// 定义一个ImageView
		 ImageView imageView = new ImageView(mContext);
		 imageView.setImageResource(R.drawable.voice_to_short); // 图标
		 
		 TextView mTv = new TextView(mContext);
		 mTv.setText(getResources().getString(R.string.record_time_is_short));
		 mTv.setTextSize(14);
		 mTv.setTextColor(Color.WHITE);//字体颜色
		 //mTv.setPadding(0, 10, 0, 0);
		 
		// 将ImageView和ToastView合并到Layout中
		 linearLayout.addView(imageView);
		 linearLayout.addView(mTv);
		 linearLayout.setGravity(Gravity.CENTER);//内容居中
		 linearLayout.setBackgroundResource(R.drawable.record_bg);//设置自定义toast的背景
		 
		 toast.setView(linearLayout); 
		 toast.setGravity(Gravity.CENTER, 0,0);//起点位置为中间     100为向下移100dp
		 toast.show();				
	}
	//获取文件手机路径
		private String getAmrPath(){
			File file = new File(Environment.getExternalStorageDirectory(), AppConfig.FOLDER_VOICE_RECORD+File.separator+date+".amr");
			return file.getAbsolutePath();
		}
		
		//录音计时线程
		private void mythread(){
			recordThread = new Thread(ImgThread);
			recordThread.start();
		}
		
		//录音Dialog图片随声音大小切换
		private void setDialogImage(){
			if (voiceValue < 200.0) {
				dialog_img.setImageResource(R.drawable.record_animate_01);
			}else if (voiceValue > 200.0 && voiceValue < 400) {
				dialog_img.setImageResource(R.drawable.record_animate_02);
			}else if (voiceValue > 400.0 && voiceValue < 800) {
				dialog_img.setImageResource(R.drawable.record_animate_03);
			}else if (voiceValue > 800.0 && voiceValue < 1600) {
				dialog_img.setImageResource(R.drawable.record_animate_04);
			}else if (voiceValue > 1600.0 && voiceValue < 3200) {
				dialog_img.setImageResource(R.drawable.record_animate_05);
			}else if (voiceValue > 3200.0 && voiceValue < 5000) {
				dialog_img.setImageResource(R.drawable.record_animate_06);
			}else if (voiceValue > 5000.0 && voiceValue < 7000) {
				dialog_img.setImageResource(R.drawable.record_animate_07);
			}else if (voiceValue > 7000.0 && voiceValue < 10000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_08);
			}else if (voiceValue > 10000.0 && voiceValue < 14000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_09);
			}else if (voiceValue > 14000.0 && voiceValue < 17000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_10);
			}else if (voiceValue > 17000.0 && voiceValue < 20000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_11);
			}else if (voiceValue > 20000.0 && voiceValue < 24000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_12);
			}else if (voiceValue > 24000.0 && voiceValue < 28000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_13);
			}else if (voiceValue > 28000.0) {
				dialog_img.setImageResource(R.drawable.record_animate_14);
			}
		}
		
		//录音线程
		private Runnable ImgThread = new Runnable() {
			@Override
			public void run() {
				recodeTime = 0.0f;
				while (RECODE_STATE==RECORD_ING) {
					if (recodeTime >= MAX_TIME && MAX_TIME != 0) {
						imgHandle.sendEmptyMessage(0);
					}else{
						try {
							Thread.sleep(200);
							recodeTime += 0.2;
							if (RECODE_STATE == RECORD_ING) {
								voiceValue = audioRecorder.getAmplitude();
								imgHandle.sendEmptyMessage(1);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
			Handler imgHandle = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 0:
						//录音超过MAX_TIME秒自动停止
						if (RECODE_STATE == RECORD_ING) {
							RECODE_STATE=RECODE_ED;
							if (dialog.isShowing()) {
								dialog.dismiss();
							}
							try{
								audioRecorder.stop();
								voiceValue = 0.0;
							} catch (IOException e) {
									e.printStackTrace();
							}
							if (recodeTime < 1.0) {
								showWarnToast();
								//SmallMoodAddRecord.setText("按住开始录音");
								RECODE_STATE=RECORD_NO;
							}else{
								//SmallMoodAddRecord.setText("录音完成!点击重新录音");
								//TODO 可以震动，或者声音提示，超时停止
								SmallMoodAddRecord.setVisibility(View.GONE);
								SmallMoodAddRecordHas.setVisibility(View.VISIBLE);
								realVoicePath = getAmrPath();
								NewDataToast.makeText(TextImageActivity.this, getResources().getString(R.string.record_time_is_out), true).show();
							}
						}
						break;
					case 1:
						setDialogImage();
						break;
					default:
						break;
					}
					
				}
			};
		};
	/**
	 * 单击事件集合
	 * @param id
	 * @param btn
	 * @return
	 */
	private View.OnClickListener BtnClick(){
		return new View.OnClickListener(){
			@SuppressWarnings("static-access")
			@Override
			public void onClick(View v) {
				alertDialog = new AlertDialog.Builder(mContext);
				alertDialog.setTitle(getResources().getString(R.string.please_select));
				alertDialog.setIcon(android.R.drawable.ic_dialog_info);
				alertDialog.setNegativeButton(getResources().getString(R.string.cancle),null);
					switch(v.getId()){
					case R.id.smallmood_add_img:
						alertDialog.setItems(R.array.smallmood_add_img_select,Img());
						alertDialog.show();
						break;
					case R.id.smallmood_add_record_has:
						if(!playState){
							alertDialog.setItems(R.array.smallmood_add_record_has_select_play,RecordHas());
						}else{
							alertDialog.setItems(R.array.smallmood_add_record_has_select_stop,RecordHas());
						}
						alertDialog.show();
						break;
					case R.id.smallmood_add_img_has:
						alertDialog.setItems(R.array.smallmood_add_img_has_select,ImgHas());
						alertDialog.show();
						break;
					case R.id.smallmood_add_back:
						
						break;
					case R.id.smallmood_add_submit:
						SubmitingDialog.show();
						new Thread(new Runnable() {
							@Override
							public void run()
							{
								String return_str = "";
								try {
									return_str = submit();
								} catch (Exception e) {
									e.printStackTrace();
								}
								Message msg_listData = new Message();
								msg_listData.obj = return_str;
								handler1.sendMessage(msg_listData);
							}
						}).start();
						
						break;
					}
				
			}
		};
	}
	 private  Handler handler1 = new Handler() {

		  public void handleMessage(Message message) {
			  if(SubmitingDialog!=null)
				  SubmitingDialog.cancel();
			  //System.out.println("message.obj = "+message.obj);
			  if (message.obj=="success") {
				  UIHelper.ToastMessage(AppContext.getInstance(), R.string.loading_success);
				  //提交成功，设置返回数据
				  resultIntent.putExtra("submit_status", "success");
				  finish();
			  }else if(message.obj=="message_is_null"){
				  UIHelper.ToastMessage(AppContext.getInstance(), R.string.smallmood_content_is_null);
				  resultIntent.putExtra("submit_status", "fail");
			  }else{
				  UIHelper.ToastMessage(AppContext.getInstance(), R.string.io_exception_error);
				  resultIntent.putExtra("submit_status", "fail");
			  }
			  	
		  }
   };
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //TODO 设置拍照照片的大小，不能上传太大的照片，无意义
        if(requestCode == RESULT_GET_CAMERA){//照相
        	if (requestCode == RESULT_GET_CAMERA && resultCode == RESULT_OK) {
        		//Bitmap bitmap = null;
//        		FileInputStream fis = null;
//        		//File file = null;
//    			try {
//    				fis = new FileInputStream(realImgPath);
//    				bitmap = BitmapFactory.decodeStream(fis);
//    				//file = new File(realImgPath);
//    			} catch (FileNotFoundException e) {
//    				e.printStackTrace();
//    				UIHelper.ToastMessage(mContext, mContext.getString(R.string.io_exception_error));
//    			} catch (@SuppressWarnings("hiding") IOException e) {
//					e.printStackTrace();
//				} finally{
//					try{
//						if(fis!=null)
//						fis.close();
//					}catch (IOException e) {
//						e.printStackTrace();
//						UIHelper.ToastMessage(mContext, mContext.getString(R.string.io_exception_error));
//					}
//				}
        		//TODO 设置拍照为屏幕大小
//        		 try  
//                 {  
//        			 super.onActivityResult(requestCode, resultCode, data);  
//        			 Bundle extras = data.getExtras();  
//    			 	 bitmap = (Bitmap) extras.get("data");  
//    			 	 ByteArrayOutputStream baos = new ByteArrayOutputStream();  
//    			 	 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
//    			 	 byte[] mContent = baos.toByteArray();  
//                 }catch ( Exception e ){  
//                	 e.printStackTrace();  
//                 }  
    			//设置图片
        		mBitmap = ImageUtils.getBitmapByPath(realImgPath);
    			SmallMoodAddImg.setVisibility(View.GONE);
    			SmallMoodAddImgHas.setVisibility(View.VISIBLE);
    			SmallMoodAddImgHas.setImageBitmap(mBitmap);
//    			bitmap.recycle();
//    			bitmap=null;
//    			System.gc();
//    			try {
//					ImageUtils.saveImageToSD(realImgPath, bitmap, 100);
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
        	}
        }else{//从相册选取
        	if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        		//Bitmap bitmap = null;
    	        Uri selectedImage = data.getData();
    	        String[] filePathColumn = { MediaStore.Images.Media.DATA };

    	        Cursor cursor = getContentResolver().query(selectedImage,
    	                filePathColumn, null, null, null);
    	        cursor.moveToFirst();

    	        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    	        String picturePath = cursor.getString(columnIndex);
    	        System.out.println("picturePath = "+picturePath);
    	        //File file = new File(picturePath);
    	        cursor.close();
    	        //mBitmap = ImageUtils.getBitmapByPath(picturePath);
    	       
    	        mBitmap = ImageUtils.loadImgThumbnail(picturePath, 120, 100);
    	        
    	        String imgName = FileUtils.getFileName(picturePath);
    	        realImgPath = AppConfig.FOLDER_IMG+File.separator+imgName;
    	        //设置图片
    			SmallMoodAddImg.setVisibility(View.GONE);
    			SmallMoodAddImgHas.setVisibility(View.VISIBLE);
    			SmallMoodAddImgHas.setImageBitmap(mBitmap);
    			try {
					ImageUtils.saveImageToSD(realImgPath, mBitmap, 100);
				} catch (IOException e) {
					e.printStackTrace();
				}

    	    }
        }
	}
	/**
	 * 播放声音，或者删除
	 * @return
	 */
	public DialogInterface.OnClickListener RecordHas(){
		return new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which==0) {
				//播放声音
					Toast.makeText(mContext, "试听",Toast.LENGTH_LONG).show();

					if (!playState) {
						mediaPlayer = new MediaPlayer();
						try
						{
							mediaPlayer.setDataSource(getAmrPath());
							mediaPlayer.prepare();
							mediaPlayer.start();
							//player.setText("正在播放");
							playState=true;
							//设置播放结束时监听
							mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
								
								@Override
								public void onCompletion(MediaPlayer mp) {
									if (playState) {
										//player.setText("播放声音");
										playState=false;
									}
								}
							});
						}
						catch (IllegalArgumentException e)
						{
							e.printStackTrace();
						}
						catch (IllegalStateException e)
						{
							e.printStackTrace();
						}
						catch (IOException e)
						{
							e.printStackTrace();
						}
					}else {
						if (mediaPlayer.isPlaying()) {
							mediaPlayer.stop();
							playState=false;
						}else {
							playState=false;
						}
						//player.setText("播放录音");
					}
					

				}
				if (which==1) {
				//删除录音
					//Toast.makeText(mContext, "删除",Toast.LENGTH_LONG).show();
					if(FileUtils.deleteFile(realVoicePath)){
						UIHelper.ToastMessage(AppContext.getInstance(), AppContext.getInstance().getResources().getString(R.string.delete_success));
						SmallMoodAddRecordHas.setVisibility(View.GONE);
		    			SmallMoodAddRecord.setVisibility(View.VISIBLE);
					}else{
						System.out.println("realVoicePath = "+realVoicePath);
						UIHelper.ToastMessage(AppContext.getInstance(), AppContext.getInstance().getResources().getString(R.string.delete_fail));
					}
				}
			}
		};
	}
	/**
	 * 拍照或者从相册选取
	 * @return
	 */
	public DialogInterface.OnClickListener Img(){
		return new DialogInterface.OnClickListener(){
			@SuppressWarnings("static-access")
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which==0) {
				//相机拍照
					//Toast.makeText(mContext, "相机拍照",Toast.LENGTH_LONG).show();
					if (FileUtils.checkSaveLocationExists()) { // 检测sd是否可用  
	                    System.out.println("SD card is not avaiable/writeable right now.");
	                    UIHelper.ToastMessage(AppContext.getInstance(),getResources().getString(R.string.SD_card_not_avaiable));
	                    return;  
	                }
					realImgPath = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
					realImgPath = FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+realImgPath;
					System.out.println("realImgPath = "+realImgPath);
	                FileUtils.creatSDDir(AppConfig.FOLDER_IMG);
	                isCamera = true;
//	                ImgFilePath = new File(realImgPath);
//	                if(ImgFilePath.exists()){
//	                	try {
//							ImgFilePath.createNewFile();
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
//	                }
	                Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(realImgPath)));//直接保存到本地磁盘上，确保图片分辨率和清晰度
	                //TODO 拍照大小为默认屏幕大小 android.media.action.IMAGE_CAPTURE
	                //Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
	                //getImageByCamera.setAction(Intent.ACTION_GET_CONTENT);
                    //startActivityForResult(intent, 1);
	                startActivityForResult(getImageByCamera, RESULT_GET_CAMERA);
				}
				if (which==1) {
				//相册选取
					//Toast.makeText(mContext, "相册选取",Toast.LENGTH_LONG).show();
					isCamera = false;
					Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, RESULT_LOAD_IMAGE);
				}
			}
		};
	}
	/**
	 * 查看图片或者删除
	 * @return
	 */
	public DialogInterface.OnClickListener ImgHas(){
		return new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which==0) {
				//查看图片
					//Toast.makeText(mContext, "查看",Toast.LENGTH_LONG).show();
					Intent intent = new Intent();
					intent.putExtra("imgstr", realImgPath);
					intent.setClass(mContext, ImageActivity.class);
					startActivity(intent);
				}
				if (which==1) {
				//重新添加图片
					UIHelper.ToastMessage(AppContext.getInstance(), AppContext.getInstance().getResources().getString(R.string.re_add));
					SmallMoodAddImgHas.setVisibility(View.GONE);
	    			SmallMoodAddImg.setVisibility(View.VISIBLE);
	    			SmallMoodAddImgHas.setImageBitmap(null);
	    			
				}
			}
		};
	}
	/**
	 * 提交数据
	 */
	@SuppressWarnings("unused")
	private String submit(){
		System.out.println("***************A*********Submit**************************");
		String return_str = "";
		resId = "-1";
		boolean hasImg = false,hasVoice = false,hasText = false;
		//判断登陆
		if(StringUtils.isEmpty(AppConfig.U_ID)){
			System.out.println("未登录，直接退出");
			//跳转到登陆界面
			return null;
		}else{
			//对密码进行加密
			UserID = AppConfig.U_ID;
			PassWD = MD5.getJiaMi(AppConfig.PassWord);
		}
		//判断是否有图片
		if(SmallMoodAddImgHas.getVisibility()==View.VISIBLE){
			System.out.println("有图片");
			String parms = "?uid="+UserID+"&passwd="+PassWD+"&id="+resId+"&sid="+sid;
			System.out.println("提交图片的url = "+HttpPath.WEB_UPLOAD+parms);
			resId = UploadUtil.uploadFile(mContext,realImgPath, HttpPath.WEB_UPLOAD, HttpPath.WEB_UPLOAD+parms);
			if(resId=="fail"){
				return_str = "fail";
				System.out.println("提交图片出错");
				return return_str;
			}
			imgServiceId = resId;
			hasImg = true;
		}
		//判断是否有语音
		if(SmallMoodAddRecordHas.getVisibility()==View.VISIBLE){
			System.out.println("有声音");
			String parms = "?uid="+UserID+"&passwd="+PassWD+"&id="+resId+"&sid="+sid;
			resId = UploadUtil.uploadFile(mContext,realVoicePath, HttpPath.WEB_UPLOAD, HttpPath.WEB_UPLOAD+parms);
			System.out.println("提交声音的url = "+HttpPath.WEB_UPLOAD+parms);
			if(resId=="fail"){
				return_str = "fail";
				return return_str;
			}
			hasVoice = true;
		}
		//判断是否有文字
		if(SmallMoodAddEdit.getText().toString().length()>0){
			if(SmallMoodAddEdit.getText().toString().length()>4){
				System.out.println("有文字");
				
			}else{
				//UIHelper.ToastMessage(mContext, mContext.getString(R.string.loading_success));
				//UIHelper.ToastMessage(mContext, mContext.getString(R.string.smallmood_content_is_short));
				System.out.println("SmallMoodAddEdit.getText().length() = "+SmallMoodAddEdit.getText().toString().length());
			}
			hasText = true;
		}
		if(hasImg||hasVoice||hasText){
			ImageText msg = new ImageText();
			msg.setImgServerId(imgServiceId);
			msg.setText(SmallMoodAddEdit.getText().toString());
			messageOperate.sendImageText(AppContext.user, msg, new BaseListener(){

				@Override
				public void onSuccess(Object o) {
					// TODO Auto-generated method stub
					UIHelper.ToastMessage(mContext, o.toString());
				}

				@Override
				public void onError(String e) {
					// TODO Auto-generated method stub
					UIHelper.ToastMessage(mContext, e);
				}
				
			});
			//提交数据信息
//			JSONObject jsonobject = new JSONObject();
//			try {
//				jsonobject.put("id", resId);
//				jsonobject.put("uid", UserID);
//				jsonobject.put("sid", sid);//用来判断是评论，还是新发表的（-1）
//				jsonobject.put("body_text", SmallMoodAddEdit.getText().toString());
//				if(StringUtils.isEmpty(resId)||resId.equals("-1")){
//				}else{
//					jsonobject.put("body_voice_seconds", (int)recodeTime+"");
//				}
//				
//			} catch (JSONException e) {
//				e.printStackTrace();
//				UIHelper.ToastMessage(AppContext.getInstance(), R.string.data_parser_failed);
//				resultIntent.putExtra("submit_status", "fail");
//			}
			//TODO 设置返回值 //return_str = ReSmallMood.Submit(jsonobject);
		}else{
			return "message_is_null";
		}
		return "success";
	}
   
	@Override
	public void finish() {
		// 设置结果，并进行传送  
		TextImageActivity.this.setResult(100, resultIntent);
		super.finish();
		 if(mBitmap != null && !mBitmap.isRecycled()){
				mBitmap.recycle();
				mBitmap = null;//这里最好加上这一句
			}
	}
   

}
